package avicti.bdp;

import avicti.bdp.dto.org.*;
import com.alibaba.fastjson2.JSON;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @金航数码科技有限责任公司
 * @作者：zhangyt
 * @邮箱：zhangyt@avic.com
 * @创建时间： 2024-09-29 17:36
 * @类说明：请填写
 * @修改记录：
 */
public class OrgTest {
    private static final String RESOURCE_URL = "http://10.216.76.254:10002/api/v1/organizations/hierarchy/management/all";

    // 定义 DM JDBC 驱动串
    static String jdbcString = "dm.jdbc.driver.DmDriver";
    // 定义 DM URL 连接串
    static String urlString = "jdbc:dm://localhost:5237";
    // 定义连接用户名
    static String userName = "MP_MDS";
    // 定义连接用户口令
    static String password = "Cape_123Cape_123";
    // 定义连接对象
    static Connection conn = null;
    static PreparedStatement statement;
    public static void main(String[] args) {
        List<OrganizationDTO> lists =getOrgInfo();
        getConnDMAndSaveData(lists);

    }
    /**
     * 请求接口API返回数据
     * @return
     */
    public static List<OrganizationDTO> getOrgInfo() {
        //步骤一：创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //步骤二：创建HTTP请求
        HttpGet httpGet = new HttpGet(RESOURCE_URL);
        httpGet.setHeader("Content-Type", "application/json");
        try {
            //步骤四：发送请求并获取响应数据
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("接收到的JSON====>>>>>"+result);
            //String jsonStr = readJson("D:\\ideaworkspace-Internet\\avicit-joinata-bdp\\bdp-dms\\src\\test\\java\\avicti\\bdp\\exp.json");
            //System.out.println("接收到的JSON====>>>>>"+jsonStr);
            List<OrganizationDTO> list = new ArrayList<OrganizationDTO>();
            List<OrganizationDTO> listOld = JSON.parseArray(result, OrganizationDTO.class);
            for (int i=0;i<listOld.size();i++){
                OrganizationDTO orgDTO = listOld.get(i);
                List<OrganizationDTO> subOrgDTOList =orgDTO.getManagementSubordinates();
                if(subOrgDTOList.size()>0){
                    pareJson(list,orgDTO);
                }else{
                    continue;
                }
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static void getConnDMAndSaveData(List<OrganizationDTO> lists) {
        try {
            //1.加载 JDBC 驱动程序
            System.out.println("Loading JDBC Driver...");
            Class.forName(jdbcString);
            //2.连接 DM 数据库
            System.out.println("Connecting to DM Server...");
            conn = DriverManager.getConnection(urlString, userName, password);
            String sql_insert = "insert into \"MP_MDS\".\"ORG_INFO\"(\"ID\", \n" +
                    "       \"PROPERTY_SUPER_IOR_ID\", \n" +
                    "       \"MANAGEMENT_SUPER_IOR_ID\", \n" +
                    "       \"REGISTERED_FULL_NAME\", \n" +
                    "       \"UNITE_SOCIALCREDIT_IDENTIFIER\", \n" +
                    "       \"DOMESTI_COVER_SEAS\", \n" +
                    "       \"GROUP_UNIFIED_UNIT_CODE\", \n" +
                    "       \"ORGANIZATION_CODE\", \n" +
                    "       \"CHINESE_FULL_NAME\", \n" +
                    "       \"CHINESE_ABBR_NAME\", \n" +
                    "       \"ENGLISH_FULL_NAME\", \n" +
                    "       \"ENGLISH_ABBR_NAME\", \n" +
                    "       \"POSTAL_CODE\", \n" +
                    "       \"COMMUNICATION_ADDRESS\", \n" +
                    "       \"FAX\", \n" +
                    "       \"CONTACT_PHONE_NUMBER\", \n" +
                    "       \"STOCK_INFO\", \n" +
                    "       \"GROUP_INTERNAL_MANAGEMENT_TYPE\", \n" +
                    "       \"MANAGEMENT_LEVEL\", \n" +
                    "       \"SIBLING_ORDER_NUMBER\", \n" +
                    "       \"EQUITY_INVESTMENT_INFO\", \n" +
                    "       \"SHARE_HOLDERS_INFO\")\n" +
                    "       VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            //3.通过连接对象创建 java.sql.Statement 对象
            statement = conn.prepareStatement(sql_insert);
            conn.setAutoCommit(false); // 开始事务
            for (int i = 0; i < lists.size(); i++) {
                OrganizationDTO org=lists.get(i);
                BusinessRegistrationInfo buReg = org.getBusinessRegistrationInfo();
                SupplementedBasicInfo sup = org.getSupplementedBasicInfo();
                CommunicationInfo comLinfo = org.getCommunicationInfo();
                StockInfo sinfo = org.getStockInfo();
                GroupInternalManagementInfo gman = org.getGroupInternalManagementInfo();
                List<EquityInvestmentInfo> lequ =  org.getEquityInvestmentInfo();
                String equityInve="";
                if(lequ.size()>0){
                    equityInve=lequ.get(0).getInvesteeName();
                }
                List<ShareholderInfo> shaList = org.getShareholdersInfo();
                String shaStr ="";
                if(shaList.size()>0){
                    shaStr=shaList.get(0).getShareholderName();
                }
                statement.setString(1, org.getId());
                statement.setString(2, org.getPropertySuperiorId());
                statement.setString(3, org.getManagementSuperiorId());
                statement.setString(4, buReg.getRegisteredFullName());
                statement.setString(5, buReg.getUnifiedSocialCreditIdentifier());
                statement.setString(6, buReg.getDomesticOverseas());
                statement.setString(7, sup.getGroupUnifiedUnitCode());
                statement.setString(8, sup.getOrganizationCode());
                statement.setString(9, sup.getChineseFullName());
                statement.setString(10,sup.getChineseAbbrName());
                statement.setString(11,sup.getEnglishFullName());
                statement.setString(12,sup.getEnglishAbbrName());
                statement.setString(13,comLinfo.getPostalCode());
                statement.setString(14,comLinfo.getCommunicationAddress());
                statement.setString(15,comLinfo.getFax());
                statement.setString(16,comLinfo.getContactPhoneNumber());
                statement.setString(17,sinfo.getStockAbbrName());
                statement.setString(18,gman.getGroupInternalManagementType());
                statement.setInt(19,gman.getManagementLevel());
                statement.setInt(20,gman.getSiblingOrderNumber());
                statement.setString(21,shaStr);
                statement.setString(22,shaStr);
                statement.addBatch(); // 添加到批处理
            }
            int[] updateCounts = statement.executeBatch(); // 执行批处理
            conn.commit(); // 提交事务
            System.out.println("Batch update counts: " + Arrays.toString(updateCounts));
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭资源
                statement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static List<OrganizationDTO> pareJson(List<OrganizationDTO> list,OrganizationDTO orgDto){
        List<OrganizationDTO> subDtoList = orgDto.getManagementSubordinates();
        if(subDtoList.size()>0){
          for(int i=0; i<subDtoList.size();i++){
              OrganizationDTO subdto = subDtoList.get(i);
              pareJson(list,subdto);
           }
        }else{
            list.add(orgDto);
        }
        return list;
    }
    /**
     * 读取json文件数据
     *
     * @param jsonPath json文件路径
     * @return 字符串
     */
    public static String readJson(String jsonPath) {
        File jsonFile = new File(jsonPath);
        try {
            FileReader fileReader = new FileReader(jsonFile);
            BufferedReader reader = new BufferedReader(fileReader);
            StringBuilder sb = new StringBuilder();
            while (true) {
                int ch = reader.read();
                if (ch != -1) {
                    sb.append((char) ch);
                } else {
                    break;
                }
            }
            fileReader.close();
            reader.close();
            return sb.toString();
        } catch (IOException e) {
           return "";
        }
    }
}
